package com.util;

import java.io.UnsupportedEncodingException;
import java.util.TimeZone;

import org.apache.http.entity.StringEntity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sys.DemoApp;

public class MgqRestClient {
	public final static String TAG = "MgqRestClient";

	private static AsyncHttpClient client = new AsyncHttpClient();

	public static void get(String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler) {
		if (params != null) {
			TLog.i(TAG, "get url:" + url + "    " + params.toString());
		}

		String _tStr;
		int _t = TimeZone.getDefault().getRawOffset()/(3600*1000);
		_tStr = String.valueOf(_t);
		if(_t > 0) _tStr = "+" + _tStr;

		url = url + "?" + "accessToken=" + PreferencesUtils.getString(DemoApp.getContext(), "accessToken") + "&_t="
				+ _tStr;
		
		client.setTimeout(30000);
		client.get(getAbsoluteUrl(url), params, responseHandler);
	}

	public static void post(String url, RequestParams params,
			AsyncHttpResponseHandler responseHandler) {
		if (params != null) {
			TLog.i(TAG, "post url:" + url + "    " + params.toString());
		}

		String _tStr;
		int _t = TimeZone.getDefault().getRawOffset()/(3600*1000);
		_tStr = String.valueOf(_t);
		if(_t > 0) _tStr = "+" + _tStr;

		url = url + "?" + "accessToken=" + PreferencesUtils.getString(DemoApp.getContext(), "accessToken") + "&_t="
				+ _tStr;
		
		client.setTimeout(60000);
		client.post(getAbsoluteUrl(url), params, responseHandler);
	}
	
	public static void postBody(String url, String params,
			AsyncHttpResponseHandler responseHandler) {
		if (params != null) {
			TLog.i(TAG, "post url:" + url + "    " + params.toString());
		}

		String _tStr;
		int _t = TimeZone.getDefault().getRawOffset()/(3600*1000);
		_tStr = String.valueOf(_t);
		if(_t > 0) _tStr = "+" + _tStr;

		url = url + "?" + "accessToken=" + PreferencesUtils.getString(DemoApp.getContext(), "accessToken") + "&_t="
				+ _tStr;
		
		client.setTimeout(60000);
		try {
			client.post(DemoApp.getContext(), getAbsoluteUrl(url), new StringEntity(params,"utf-8"), 
					"text/html;charset=utf-8", responseHandler);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private static String getAbsoluteUrl(String relativeUrl) {
		return relativeUrl;
	}
}
